import sys
import pygame
from setting import setting
from ship import Ship
from bullet import Bullet
class AlienInvasion:
    def __init__(self):
        '''初始化游戏和调节窗口大小'''
        pygame.init()
        '''引入设定'''
        self.setting=setting()
        '''是否全屏'''
        if self.setting.screen_style=='FULLSCREEN':
            self.screen=pygame.display.set_mode((0,0),pygame.FULLSCREEN)
            self.setting.screen_height=self.screen.get_rect().height
            self.setting.screen_width=self.screen.get_rect().width
        else:
            self.screen=pygame.display.set_mode((self.setting.screen_width,self.setting.screen_height))
        pygame.display.set_caption('Alien Invasion')
        '''引入船'''
        self.ship=Ship(self)
        '''用于储存子弹的编组'''
        self.bullets=pygame.sprite.Group()
    def run_game(self):
        '''开始游戏的主循环'''
        while True:
            self._check_events() 
            self.ship.update()
            self.bullets.update()
            self._update_screen()
            '''删除多余的子弹'''
            for bullet in self.bullets.copy():
                if bullet.rect.bottom<=0:
                    self.bullets.remove(bullet)
            #print(len(self.bullets))
    def _check_events(self):
        '''监视屏幕和鼠标事件'''
        for event in pygame.event.get():
            if event.type==pygame.QUIT:
                sys.exit()
            elif event.type==pygame.KEYDOWN:
                self._checkout_keydown_event(event)
            elif event.type==pygame.KEYUP:
                self._checkout_keyup_event(event)
    def _update_screen(self):
        '''每次循环时候绘制颜色和船'''
        self.screen.fill(self.setting.bg_color)
        self.ship.blitme()
        for bullet in self.bullets.sprites():
            bullet.draw_bullet()
        '''让绘制的屏幕可见'''
        pygame.display.flip()
    def _checkout_keydown_event(self,event):
            if event.key==pygame.K_RIGHT:
                self.ship.moving_right=True
            elif event.key==pygame.K_q:
                sys.exit()
            elif event.key==pygame.K_LEFT:
                self.ship.moving_left=True
            elif event.key==pygame.K_SPACE:
                self._fire_bullet()
    def _checkout_keyup_event(self,event):
            if event.key==pygame.K_RIGHT:
                self.ship.moving_right=False
            elif event.key==pygame.K_LEFT:
                self.ship.moving_left=False
    def _fire_bullet(self):
        '''创建一个子弹'''
        if len(self.bullets)<self.setting.bullet_allowed:
            new_bullet=Bullet(self)
            self.bullets.add(new_bullet)
    def _update_bullet(self):
        '''更新子弹位置并删除消失的子弹'''
        self.bullets.update()
        for bullet in self.bullets.copy():
                if bullet.rect.bottom<=0:
                    self.bullets.remove(bullet)
            #print(len(self.bullets))
if __name__=='__main__':
#  创建游戏并运行
    ai=AlienInvasion()
    ai.run_game()
